package com.runen.wnhz.runen.common.login.Wx;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;
import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.common.aspectj.CheckNet;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

/**
 * 微信登录代理Activity
 */
public class WXLoginActivity extends Activity implements WxProxyActivity {

    public static final String STATE = "wechat_unohacha_qqj";
    private Context mContext;
    private WeiXinUtils mUtils;
    private WXCallBack mCallBack;
    private Gson mGson;
    private String mWxToken;
    private String mWxOpenId;
    private String mWxRefreshToken;

    private final String[] WX_PERMISSION = new String[]{
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wxlogin);

        this.mContext = WXLoginActivity.this;
        this.mUtils = WeiXinUtils.getInstance();
        this.mCallBack = mUtils.getWxCallBack();
        this.mWxToken = getIntent().getStringExtra("WxToken");
        this.mWxOpenId = getIntent().getStringExtra("WxOpenId");
        this.mWxRefreshToken = getIntent().getStringExtra("WxRefreshToken");
        this.mGson = new Gson();

        mUtils.setWxProxyActivity(this);
        if (!mUtils.getWxApi().isWXAppInstalled()) {
            WXAppNotInstalled();
        } else {
            if (TextUtils.isEmpty(mWxToken)) {
                //拉起微信授权登录页面
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = STATE;
                mUtils.getWxApi().sendReq(req);
            } else {
                // 检测token是否过期
                isWxTokenOk(mWxToken, mWxOpenId, mWxRefreshToken);
            }
        }
    }

    private void WXAppNotInstalled() {
        Toast.makeText(mContext, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
        close();
    }

    /**
     * 判断token是否过期
     *
     * @param wxToken
     * @param wxOpenId
     * @param wxRefreshToken
     */
    @CheckNet
    public void isWxTokenOk(final String wxToken, final String wxOpenId, final String wxRefreshToken) {
        OkHttpUtils.get()
                .url("https://api.weixin.qq.com/sns/auth")
                .addParams("access_token", wxToken)
                .addParams("openid", wxOpenId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(mContext, "微信token检测失败", Toast.LENGTH_SHORT).show();
                        close();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        WxLoginCode code = mGson.fromJson(response, WxLoginCode.class);
                        if (code == null) {
                            Toast.makeText(mContext, "微信检测信息解析失败", Toast.LENGTH_SHORT).show();
                            close();
                        } else {
                            if (code.getErrcode() == 0) {
                                //token有效 获取信息
                                getWxInfo(wxToken, wxOpenId);
                            } else {
                                //token失效 刷新token
                                refreshToken(wxRefreshToken);
                            }
                        }
                    }
                });
    }

    /**
     * 刷新token
     *
     * @param wxRefreshToken
     */
    @CheckNet
    public void refreshToken(final String wxRefreshToken) {
        OkHttpUtils.get()
                .url("https://api.weixin.qq.com/sns/oauth2/refresh_token")
                .addParams("appid", mUtils.getWxAppID())
                .addParams("refresh_token", wxRefreshToken)
                .addParams("grant_type", "refresh_token")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(mContext, "微信token刷新失败", Toast.LENGTH_SHORT).show();
                        close();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        WxLoginInfo info = mGson.fromJson(response, WxLoginInfo.class);
                        if (info == null) {
                            Toast.makeText(mContext, "微信刷新信息解析失败", Toast.LENGTH_SHORT).show();
                            close();
                        } else {
                            if (info.getErrcode() == 40030) {
                                //刷新token过期，重新授权
                                SendAuth.Req req = new SendAuth.Req();
                                req.scope = "snsapi_userinfo";
                                req.state = STATE;
                                mUtils.getWxApi().sendReq(req);
                            } else {
                                // 保存token信息
                                if (mCallBack != null) {
                                    mCallBack.saveLoginInfo(info);
                                }
                                getWxInfo(info.getAccess_token(), info.getOpenid());
                            }
                        }
                    }
                });
    }

    /**
     * 获取微信用户信息
     *
     * @param wxToken
     * @param wxOpenId
     */
    @CheckNet
    public void getWxInfo(String wxToken, String wxOpenId) {
        OkHttpUtils.get()
                .url("https://api.weixin.qq.com/sns/userinfo")
                .addParams("access_token", wxToken)
                .addParams("openid", wxOpenId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        // 获取用户信息失败
                        Toast.makeText(mContext, "微信用户信息获取失败", Toast.LENGTH_SHORT).show();
                        close();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        WxLoginUserInfo info = mGson.fromJson(response, WxLoginUserInfo.class);
                        if (info != null) {
                            // 用户信息获取成功
                            if (mCallBack != null) {
                                mCallBack.saveUserInfo(info);
                            }
                        } else {
                            // 用户信息解析失败
                            Toast.makeText(mContext, "微信用户信息解析失败", Toast.LENGTH_SHORT).show();
                        }
                        close();
                    }
                });
    }

    /**
     * 通过code获取access_token的接口。
     *
     * @param code
     */
    @CheckNet
    public void getWxToken(String code) {
        OkHttpUtils.get()
                .url("https://api.weixin.qq.com/sns/oauth2/access_token")
                .addParams("appid", mUtils.getWxAppID())
                .addParams("secret", mUtils.getWxSecret())
                .addParams("code", code)
                .addParams("grant_type", "authorization_code")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        // 微信token获取失败
                        Toast.makeText(mContext, "微信token获取失败", Toast.LENGTH_SHORT).show();
                        close();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        WxLoginInfo info = mGson.fromJson(response, WxLoginInfo.class);
                        if (info != null) {
                            // 保存token信息
                            if (mCallBack != null) {
                                mCallBack.saveLoginInfo(info);
                            }
                            getWxInfo(info.getAccess_token(), info.getOpenid());
                        } else {
                            // 微信token 解析失败
                            Toast.makeText(mContext, "微信token解析失败", Toast.LENGTH_SHORT).show();
                            close();
                        }
                    }
                });
    }

    @Override
    public void onWXEntryActivityResult(String code) {
        getWxToken(code);
    }

    @Override
    public void onCancel() {
        close();
    }

    @Override
    public void onDenied() {
        close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUtils.setWxProxyActivity(null);
    }

    public void close(){
        finish();
        overridePendingTransition(0, 0);
    }
}
